<template>
    <BasePage>
        <el-form slot="form" :inline="true" size="medium" @submit.native.prevent>
            <el-form-item label="公路名称">
                <RoadSelect :value.sync="form.highwayName" :is-label="true" placeholder="请选择" clearable />
            </el-form-item>
            <el-form-item label="年度">
                <el-date-picker v-model="form.year" type="year" value-format="yyyy" :editable="false" placeholder="请选择" />
            </el-form-item>
            <el-form-item label="管理机构">
                <el-cascader
                    v-model="form.orgs"
                    :props="props"
                    :options="orgOptions"
                    clearable
                    :show-all-levels="false"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="setOrgId"
                />
            </el-form-item>
            <el-form-item>
                <BaseButton v-permission="{ btnCode: 'dlyh_c14_d52_2' }" @click="handleFilter">查询</BaseButton>
                <BaseButton type="second" @click="resetConditions">重置</BaseButton>
            </el-form-item>
        </el-form>

        <div slot="button">
            <BaseButton v-permission="{ btnCode: 'dlyh_c14_d54_2' }" @click="showDialog()">新建年度计划</BaseButton>
            <FormDialog
                ref="dateDialog"
                :props="cascaderProps"
                :title="dialogTitle"
                :items="formItems"
                :rules="dialogRules"
                :form.sync="dialogForm"
                :visible.sync="dialogVisible"
                @submit="handleAdd"
            />
        </div>

        <!--数据列表区-->
        <BaseTable slot="table" v-loading="listLoading" :columns="columns" :data="list" row-key="id" height="calc(100% - 73px)" highlight-current-row>
            <template #number="{ scope: { row } }">
                <BaseButton type="text" @click="handleDetail(row)">{{ row.number }}</BaseButton>
            </template>
            <template #type="{ scope: { row } }">
                <span :style="`color:${changeTypesColor[row.changeType]};`">{{ changeTypes[row.changeType] }}</span>
            </template>
            <template #status="{ scope: { row } }">
                <span :style="`color:${statusColor[row.status]};`">{{ row.status | value2Name(checkTypes) }}</span>
            </template>
            <template #orgDept="{ scope: { row } }">
                <span>{{ row.orgDept || '-' }}</span>
            </template>
            <template #handle="{ scope: { row } }">
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c14_d56_2' }" type="text" @click="handleSubmit(row.number)">
                    提交
                </BaseButton>
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c14_d57_2' }" type="text" @click="handleEdit(row)"> 编辑</BaseButton>
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c14_d58_2' }" type="text" color="danger" @click="handleDelete(row.id)">
                    删除
                </BaseButton>

                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c14_d56_2' }" type="text" @click="handlerecall(row.number)">
                    撤回
                </BaseButton>

                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c14_d120_2' }" type="text" @click="handleCheck(row)"> 审核</BaseButton>
                <BaseButton v-show="row.status === 2" v-permission="{ btnCode: 'dlyh_c14_d121_2' }" type="text" @click="handleApproval(row)"> 批复</BaseButton>
                <BaseButton v-show="row.status === 3 && !row.month" v-permission="{ btnCode: 'dlyh_c14_d55_2' }" type="text" @click="showDialog(row)">
                    新建下级
                </BaseButton>

                <!-- 变更功能下期迭代开发 -->
                <!-- <BaseButton v-if="row.status === 3 && row.recordType !== 2" type="text" @click="submitChange(row)">提交变更</BaseButton>
                <BaseButton v-if="row.status === 3 && row.recordType === 2" type="text" @click="checkChange(row)">查看变更</BaseButton> -->
            </template>
        </BaseTable>
        <!--分页组件-->
        <Pagination
            slot="pagination"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @current-change="getList"
            @size-change="getList"
        />
    </BasePage>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { RoadPlanModel, OrgModel, BudgetingOldModel } from '@/models'
import reconfirm from '@/utils/reconfirm'
import { CheckTypes, StatusColor, QuarterOptions, ChangeTypes, ChangeTypesColor, QuarterMap } from '@/config/constants'
import { value2Name } from '@/filters'
import roadInfo from '../../mixins/road-info'
import KeepAliveHandler from '@/mixins/keepAliveHandler'

export default {
    name: 'RoadPlanIndex',
    components: {
        BasePage
    },
    filters: {
        value2Name
    },
    mixins: [
        roadInfo,
        KeepAliveHandler({
            defaultCondition: {
                highwayName: null,
                year: null,
                orgs: [],
                orgId: null
            },
            conditionObjKey: 'form'
        })
    ],
    data() {
        return {
            checkTypes: CheckTypes,
            statusColor: StatusColor,
            changeTypes: ChangeTypes,
            changeTypesColor: ChangeTypesColor,
            model: new RoadPlanModel(),
            orgModel: new OrgModel(),
            budgetingModel: new BudgetingOldModel(),
            form: {
                highwayName: null,
                year: null,
                orgs: []
            },
            orgOptions: [],
            props: {
                value: 'id',
                label: 'name',
                checkStrictly: true
            },
            dialogTitle: '请选择年度',
            dialogVisible: false,
            dialogForm: {},
            formItems: [],
            dialogRules: {
                budget: [{ required: true, message: '请选择预算', trigger: ['blur', 'change'] }],
                quarter: [{ required: true, message: '请选择季度', trigger: ['blur', 'change'] }],
                month: [{ required: true, message: '请选择月份', trigger: ['blur', 'change'] }]
            },
            listLoading: true,
            list: [],
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: Object.freeze([
                {
                    slot: 'number',
                    attrs: {
                        prop: 'number',
                        label: '编号',
                        width: '220',
                        'show-overflow-tooltip': true,
                        fixed: 'left'
                    }
                },
                {
                    attrs: {
                        prop: 'highwayName',
                        label: '公路名称',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'cycle',
                        label: '周期',
                        'show-overflow-tooltip': true,
                        width: '140'
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        prop: 'recordType',
                        label: '类型',
                        width: '100',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'orgDept',
                    attrs: {
                        prop: 'orgDept',
                        label: '管理机构',
                        'show-overflow-tooltip': true,
                        'min-width': '200'
                    }
                },
                {
                    attrs: {
                        prop: 'routeLength',
                        label: '路线长度（km）',
                        'show-overflow-tooltip': true,
                        width: '180'
                    }
                },
                {
                    attrs: {
                        prop: 'total',
                        label: '合计（元）',
                        'show-overflow-tooltip': true,
                        width: '180'
                    }
                },
                {
                    slot: 'status',
                    attrs: {
                        prop: 'status',
                        label: '状态',
                        width: '100',
                        'show-overflow-tooltip': true,
                        fixed: 'right'
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        'min-width': '240',
                        fixed: 'right'
                    }
                }
            ]),
            userId: null,
            year: null,
            planType: 1, // 计划类型 1-年度计划，2-季度计划，3-月度计划
            roadCode: null,
            number: null,
            cascaderProps: {
                value: 'code',
                label: 'name',
                checkStrictly: false
            },
            BudgetList: [],
            rowData: {}
        }
    },
    created() {
        this.userId = this.$store.getters.avatar.id
        this.getOrgAll()
        this.getList()
        this.getBudgetListByRoad()
    },
    methods: {
        getBudgetListByRoad() {
            this.budgetingModel.getBudgetListByRoad().then((res) => {
                this.BudgetList = res
            })
        },
        getbudgetPeriodList(data) {
            return this.budgetingModel.getPeriodList(data)
        },
        getPeriodList(data) {
            return this.model.getPeriodList(data)
        },
        handleCheck(row) {
            this.$router.push({
                name: 'RoadPlanAudit',
                query: {
                    number: row.number,
                    belongItem: 2,
                    type: row.recordType,
                    planType: row.planType,
                    audit: true
                }
            })
        },
        handleApproval(row) {
            // belongItem所属项(1-养护预算、2-养护计划、3-计划实施、4-路产赔付、5-巡查计划)
            this.$router.push({
                name: 'RoadPlanApproval',
                query: {
                    number: row.number,
                    belongItem: 2,
                    type: row.recordType,
                    planType: row.planType,
                    audit: true,
                    approval: true
                }
            })
        },
        handlerecall(number) {
            reconfirm({
                text: '是否确定撤回表单',
                callback: () => this.recall(number)
            })
        },
        recall(number) {
            return this.model
                .recall(number)
                .then(() => {
                    this.getList()
                    this.$message.success('撤回成功！')
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        handleSubmit(number) {
            reconfirm({
                text: '是否确定提交表单',
                callback: () => this.submit(number)
            })
        },
        submit(number) {
            return this.model
                .submit(number)
                .then(() => {
                    this.getList()
                    this.$message.success('提交成功！')
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 机构筛选框变化时，把默认的orgs数组处理成origId参数
        setOrgId(val) {
            if (val.length > 0) {
                this.form.orgId = val[val.length - 1]
            } else {
                this.form.orgId = null
            }
        },
        // 获取机构下拉项
        getOrgAll() {
            this.orgModel.getListAll().then((res) => {
                this.orgOptions = res
            })
        },
        getList() {
            this.listLoading = true
            this.model
                .getList(this.form, this.page)
                .then((res) => {
                    this.list = res.list
                    this.page.total = res.totalCount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 查询
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        handleDelete(id) {
            reconfirm({
                callback: () => this.delete(id)
            })
        },
        delete(id) {
            return this.model.delete({ id }).then(() => {
                this.getList()
                this.$message.success('删除成功!')
            })
        },
        handleDetail(row) {
            this.$router.push({ path: 'detail', query: { number: row.number, planType: row.planType } })
        },
        // 提交变更
        submitChange(row = {}) {
            switch (row.planType) {
                case 1:
                    this.$router.push({
                        path: 'change',
                        query: {
                            type: 'change',
                            number: row.number
                        }
                    })
                    break
                case 2:
                    this.$router.push({
                        path: 'quarter-change',
                        query: {
                            type: 'change',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            roadCode: row.roadCode
                        }
                    })
                    break
                case 3:
                    this.$router.push({
                        path: 'month-change',
                        query: {
                            type: 'change',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            month: row.month,
                            roadCode: row.roadCode
                        }
                    })
                    break
            }
        },
        // 查看变更
        checkChange(row) {
            this.$router.push({ path: 'detail', query: { number: row.changeNumber, planType: row.planType, recordType: row.recordType } })
        },
        async showDialog(row = {}) {
            // 用于新建下级时使用
            this.rowData = row

            this.planType = row.planType ? row.planType + 1 : 1
            this.year = row.year || ''
            this.quarter = row.quarter || ''
            this.roadCode = row.roadCode || ''
            this.number = row.number || null
            this.dialogForm = {}
            // planType:计划类型 1-年度计划，2-季度计划，3-月度计划
            // 年度计划1时，新增的是季度；季度计划2时，新增的是月度
            switch (this.planType) {
                case 1: {
                    this.dialogTitle = '请选择年度'
                    this.dialogForm = {}
                    this.formItems = [
                        {
                            type: 'cascader',
                            model: 'budget',
                            label: '预算',
                            showAllLevels: true,
                            options: this.BudgetList
                        }
                    ]
                    // 这里不做await阻塞，否则会导致弹框打开不灵敏，影响体验
                    this.getPeriodList().then((planList) => {
                        this.BudgetList.forEach((item) => {
                            planList.forEach((m) => {
                                if (m.roadCode === item.code) {
                                    item.children.forEach((k) => {
                                        if (k.code === m.year) {
                                            k.disabled = true
                                            console.log(k)
                                        }
                                    })
                                }
                            })
                        })
                    })

                    break
                }
                case 2: {
                    this.dialogTitle = `请选择${row.year}年季度`
                    this.formItems = [
                        {
                            type: 'select',
                            model: 'quarter',
                            label: '季度',
                            options: QuarterOptions
                        }
                    ]

                    const data = {
                        roadCode: row.roadCode,
                        year: row.year
                    }
                    Promise.all([this.getbudgetPeriodList(data), this.getPeriodList(data)]).then((res) => {
                        const options = JSON.parse(JSON.stringify(this.formItems[0].options))

                        // 获取到已经创建预算的列表，没有预算的禁止选择
                        options.forEach((item) => {
                            if (!res[0].some((m) => m.quarter === item.value)) {
                                // item.label = item.label + '(无预算)'
                                item.disabled = true
                            }
                        })
                        // 获取到已经创建的计划列表，已经创建的禁止选择
                        res[1].forEach((item) => {
                            options.forEach((m) => {
                                if (m.value === item.quarter) {
                                    // m.label = m.label + '(已创建)'
                                    m.disabled = true
                                }
                            })
                        })
                        // 重新赋值更新下表单选项
                        this.formItems = [
                            {
                                type: 'select',
                                model: 'quarter',
                                label: '季度',
                                options
                            }
                        ]
                    })
                    break
                }
                case 3: {
                    this.dialogTitle = `请选择${row.year}年${row.quarter}季度月度`
                    this.formItems = [
                        {
                            type: 'picker',
                            model: 'month',
                            label: '月度',
                            pikerType: 'month',
                            defaultValue: row.year.toString(),
                            class: 'disabled-year',
                            format: 'M'
                        }
                    ]
                    const data = {
                        roadCode: row.roadCode,
                        year: row.year,
                        quarter: row.quarter
                    }
                    Promise.all([this.getbudgetPeriodList(data), this.getPeriodList(data)]).then((res) => {
                        this.formItems = [
                            {
                                type: 'picker',
                                model: 'month',
                                label: '月度',
                                pikerType: 'month',
                                defaultValue: row.year.toString(),
                                class: 'disabled-year',
                                format: 'M',
                                pickerOptions: {
                                    disabledDate(time) {
                                        const month = time.getMonth() + 1
                                        // 获取当前日历月份，小于对应季度的最小月份和大于最大月份的都禁止选择
                                        const disabled = month < QuarterMap[row.quarter][0] || month > QuarterMap[row.quarter][2]

                                        // 获取已经有的预算，没有的预算月份不让选择
                                        let isBudget = false
                                        if (!res[0].some((item) => Number(item.month) === month)) {
                                            isBudget = true
                                        }

                                        // 获取已经新建的月份，如果有也禁止选择
                                        let isPlan = false
                                        res[1].forEach((item) => {
                                            if (Number(item.month) === month) {
                                                isPlan = true
                                            }
                                        })

                                        // 有一个为true就不让选择
                                        return disabled || isPlan || isBudget
                                    }
                                }
                            }
                        ]
                    })
                    break
                }
            }
            this.$refs['dateDialog'].show()
        },
        handleAdd(valid) {
            if (valid) {
                this.dialogVisible = false
                // getRoadName 混淆中的方法
                let road = this.rowData.roadCode
                    ? {
                        roadCode: this.rowData.roadCode,
                        highwayName: this.rowData.highwayName,
                        routeLength: this.rowData.routeLength || null,
                        orgId: this.rowData.orgId || null,
                        orgDept: this.rowData.orgDept || null
                    }
                    : this.getRoadName(this.dialogForm.budget[0])
                // 对road对象做下转义
                road = encodeURIComponent(JSON.stringify(road))
                switch (this.planType) {
                    case 1:
                        this.$router.push({
                            path: 'add',
                            query: {
                                type: 'add',
                                number: this.number,
                                year: this.dialogForm.budget[1],
                                planType: 1,
                                road
                            }
                        })
                        break
                    case 2:
                        console.log('aa', this.dialogForm.quarter)
                        this.$router.push({
                            path: 'quarter-add',
                            query: {
                                type: 'add',
                                year: this.year,
                                quarter: this.dialogForm.quarter,
                                number: this.number,
                                planType: 2,
                                road
                            }
                        })
                        break
                    case 3:
                        this.$router.push({
                            path: 'month-add',
                            query: {
                                type: 'add',
                                year: this.year,
                                quarter: this.quarter,
                                month: this.dialogForm.month, // 去除月份前的0
                                number: this.number,
                                planType: 3,
                                road
                            }
                        })
                        break
                }
            }
        },
        handleEdit(row) {
            switch (row.planType) {
                case 1:
                    this.$router.push({
                        path: 'edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            change: row.changeId,
                            year: row.year,
                            roadCode: row.roadCode
                        }
                    })
                    break
                case 2:
                    this.$router.push({
                        path: 'quarter-edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            roadCode: row.roadCode,
                            change: row.changeId
                        }
                    })
                    break
                case 3:
                    this.$router.push({
                        path: 'quarter-edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            month: row.month,
                            roadCode: row.roadCode,
                            change: row.changeId
                        }
                    })
                    break
            }
        }
    }
}
</script>

<style lang="scss">
// 在选择月份时，禁止切换年份
.disabled-year .el-date-picker__header {
    pointer-events: none;
}
</style>
